﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Aspfm.Dal;
using System.Net;
using System.IO;
using System.Collections;
using Aspfm.Main;

namespace Aspfm.DataBase
{
    public partial class UcFtp : UserControl
    {
        IDbHelper idb = null;

        public UcFtp()
        {
            InitializeComponent();
            groupBox1.Enabled = false;
            

            textBox8.Text = @"
create table Aspfm_Files
(
       filepkid varchar2(30),
       filename varchar2(200),
       filepath varchar2(200),
       ftpUptime date,
       ftpUpUser varchar2(100),
       LastWriter date,
       fftpkey varchar2(30),
       ispwd number,
       filesize number
);
-- 设置主键
alter table Aspfm_FILES
  add constraint pk_Aspfm_files primary key (FILEPKID);
  
  comment on column Aspfm_FILES.filename
  is '文件名';
comment on column Aspfm_FILES.filepath
  is '路径';
comment on column Aspfm_FILES.ftpuptime
  is '上传时间';
comment on column Aspfm_FILES.ftpupuser
  is '上传用户';
comment on column Aspfm_FILES.lastwriter
  is '文件最后修改时间';
comment on column Aspfm_FILES.ftpkey
  is 'FTP关键字';
comment on column Aspfm_FILES.ispwd
  is '是否加密，如果加密，解压密码是filepkid';
comment on column Aspfm_FILES.filesize
  is '文件大小';

create table Aspfm_FILES_CONFIG
(
  ftpkey  VARCHAR2(30) not null,
  ftptype NUMBER default 0,
  ftpip   VARCHAR2(100),
  ftpport NUMBER,
  ftpuser VARCHAR2(100),
  ftppwd  VARCHAR2(100),
  ftppath VARCHAR2(500)
);
alter table Aspfm_FILES_CONFIG
  add constraint pk_Aspfm_Files_config primary key (FTPKEY);
comment on column Aspfm_FILES_CONFIG.ftpkey
  is 'FTP关键字';
comment on column Aspfm_FILES_CONFIG.ftptype
  is '0:FTP,1:HTTP';

create or replace view Aspfm_FILES_Full as
select t.*,c.* from Aspfm_FILES t left join Aspfm_files_config c on t.fftpkey=c.ftpkey";
        }

        public void Init()
        {
            treeView1.Nodes.Clear();
            DataSourceList datalist = ConfigTool.ReadConn();
            string msg = "";
            if (datalist != null)
            {
                foreach (DataSource data in datalist.dataList)
                {
                    if (data.Key.ToLower() == "default")
                    {
                        if (DbTool.TestConn(ref msg, data))
                        {
                            idb = DbFactory.GetDB();
                        }
                        else
                        {
                            idb = null;
                        }
                        break;
                    }
                }
            }
            if (idb == null)
            {
                MessageBox.Show("请确认默认数据库连接正常。并已经保存。" + msg);
                button3.Enabled = false;
            }
            else
            {
                button3.Enabled = true;
                DataSet ds = idb.QuerySql("select * from Aspfm_FILES_CONFIG");
                bool haddef = false;
                if (DbFactory.CheckDSHadRow(ds))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        TreeNode node = treeView1.Nodes.Add(dr["ftpkey"].ToString());
                        node.Tag = dr;
                    }
                }
                foreach (TreeNode node in treeView1.Nodes)
                {
                    if (node.Text == "default")
                    {
                        haddef = true;
                    }
                }
                if (!haddef)
                {
                    treeView1.Nodes.Add("default");
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                if (textBox6.Text.Trim() == "" ||
                    textBox2.Text.Trim() == "" ||
                     textBox3.Text.Trim() == "" ||
                     textBox4.Text.Trim() == "" ||
                     textBox5.Text.Trim() == "")
                {
                    MessageBox.Show("必填项没有填写完整。");
                    return;
                }
                int port=0;
                if (!int.TryParse(textBox3.Text, out port))
                {
                    MessageBox.Show("端口要为数字。");
                    return;
                }
            }
            else
            {
                textBox2.Text = "";
                textBox3.Text = "0";
                if (textBox6.Text.Trim() == "" ||
                   textBox7.Text=="")
                {
                    MessageBox.Show("必填项没有填写完整。");
                    return;
                }
                if (!System.IO.Directory.Exists(textBox7.Text))
                {
                    string tempfile = BaseAshx.CurrentPath(false) + "\\" + textBox7.Text;
                    if (!System.IO.Directory.Exists(tempfile))
                    {
                        MessageBox.Show(textBox7.Text + "目录不存在。");
                        return;
                    }
                }
            }
            string ftpkey = textBox6.Text.ToLower().Trim();
            foreach (TreeNode node in treeView1.Nodes)
            {
                if (treeView1.SelectedNode !=node &&  node.Text.ToLower() == ftpkey)
                {
                    MessageBox.Show("Ftp关键字不允许重复。");
                    return;
                }
            }
            if (!idb.ExistTableOrView("Aspfm_FILES"))
            {
                MessageBox.Show("默认数据库：不存在文件表：Aspfm_FILES");
                return;
            }
            if (!idb.ExistTableOrView("Aspfm_FILES_CONFIG"))
            {
                MessageBox.Show("默认数据库：不存在文件表：Aspfm_FILES_CONFIG");
                return;
            }
            if (!idb.ExistTableOrView("Aspfm_FILES_Full"))
            {
                MessageBox.Show("默认数据库：不存在文件视图：Aspfm_FILES_Full");
                return;
            }
            if (checkBox1.Checked)
            {
                string textpath = "测试文件夹" + Guid.NewGuid().ToString();
                string ftperrmsg = MakeDir(textpath, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text);
                if (ftperrmsg != "")
                {
                    MessageBox.Show("ftp测试不通过：" + ftperrmsg);
                    return;
                }
                if (textBox7.Text != "")
                {
                    if (!Directory.Exists(textBox7.Text.Trim('\\') + "\\" + textpath))
                    {
                        MessageBox.Show("ftp根目录与FTP文件夹不一致。");
                        return;
                    }
                }
            }
            AspfmModel dynobj = new AspfmModel();
            dynobj.Values.Add("ftpkey", ftpkey);
            dynobj.Values.Add("ftptype", 0);
            dynobj.Values.Add("ftpip", textBox2.Text);
            dynobj.Values.Add("ftpport", textBox3.Text);
            dynobj.Values.Add("ftpuser", textBox4.Text);
            dynobj.Values.Add("ftppwd", textBox5.Text);
            dynobj.Values.Add("ftppath", textBox7.Text.Trim().Trim('\\'));
            idb.SaveData("Aspfm_FILES_CONFIG", dynobj, "ftpkey");
            Init();
            MessageBox.Show("保存成功。");
        }

        public string MakeDir(string dirName, string ip, string part, string ftpUserID, string ftpPassword)
        {
            try
            {
                // dirName = name of the directory to create.
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ip + ":" + part + "/" + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "";
        }

        private void UcFtp_Load(object sender, EventArgs e)
        {
            //if (Form1.datalist != null && Form1.datalist.ftpList != null && Form1.datalist.ftpList.Count > 0)
            //{
            //    foreach (DataParams dp in Form1.datalist.DataParamsList)
            //    {
            //        TreeNode node = new TreeNode(dp.Key);
            //        node.Tag = dp;
            //        treeView1.Nodes[0].Nodes.Add(node);
            //    }
            //}
            //if (Form1.datalist.ftpList == null)
            //    Form1.datalist.ftpList = new List<FtpInfo>();
            treeView1.Nodes[0].ExpandAll();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e != null && e.Node != null && e.Node.Tag is DataRow)
            {
                DataRow dr = (DataRow)e.Node.Tag;
                textBox6.Text = dr["ftpKey"].ToString();
                textBox2.Text = dr["ftpip"].ToString();
                textBox3.Text = dr["ftpport"].ToString();
                textBox4.Text = dr["ftpuser"].ToString();
                textBox5.Text = dr["ftppwd"].ToString();
                textBox7.Text = dr["ftpPath"].ToString();
                checkBox1.Checked = false;
                if (textBox2.Text != "")
                {
                    checkBox1.Checked = true;
                }
            }
            else
            {
                textBox6.Text = "default";
                checkBox1.Checked = false;
                textBox2.Text ="";
                textBox3.Text = "";
                textBox4.Text = "";
                textBox5.Text = "";
                textBox7.Text = "";
            }
            if (textBox6.Text.ToLower() == "default")
            {
                textBox6.ReadOnly = true;
            }
            else
            {
                textBox6.ReadOnly = false;
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            treeView1.SelectedNode = null;
            checkBox1.Checked = false;
            textBox6.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox7.Text = "";
            textBox6.ReadOnly = false;
        }

        private void 删除FfpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView1.SelectedNode;
            if (node != null && node.Text.ToLower() != "default")
            {
                DialogResult dia = MessageBox.Show("是否确定删除？", "删除提示", MessageBoxButtons.YesNo);
                if (dia == DialogResult.Yes)
                {
                    DialogResult dia1 = MessageBox.Show("请再次确认删除，不建议删除。", "删除提示", MessageBoxButtons.YesNo);
                    if (dia1 == DialogResult.Yes)
                    {
                        if (node.Tag is DataRow)
                        {
                            idb.ExecSql("delete Aspfm_FILES_CONFIG where ftpKey=st(0)",node.Text);
                            node.Remove();
                        }
                    }
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            groupBox1.Enabled = checkBox1.Checked;
        }
    }
}
